package com.rrd.dw.mr.gzip.kafka;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ucredit.babel.common.model.BaseModel;
import com.ucredit.babel.common.model.RecordType;
import com.ucredit.babel.common.model.credit.*;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper.Context;

import java.io.IOException;

/**
 * 黑卡特征拍平表
 *
 * @author guoqiang
 */

public class heikaFeatureRecordParse extends ParseBase {
    private Text val = new Text();
    private Text key = new Text();

    /**
     * 黑卡特征拍平表
     *
     * @param model
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    public boolean parseJob(Context context, BaseModel<?> model, String successful) throws IOException, InterruptedException {
        FundsCreditRecord obj = (FundsCreditRecord) model;
        StringBuilder sb = getBaseInfo(obj, successful);
        sb.append(formatValue(obj.getLoanId())).append(CRT001);
        StringBuilder TxSb = new StringBuilder(500);
        FundsCreditData data = obj.getData() == null ? new FundsCreditData() : obj.getData();
        CreditScore creditObj = data.getCreditScore();
        if(creditObj == null){
            return false;
        }
        HeiKaCreditScore heikaObj = creditObj.getHeiKaCreditScore();
        if(heikaObj == null){
            return false;
        }
        HeiKaCreditScoreData heikData = heikaObj.getData();
        if(heikData == null){
            return false;
        }
        String feature = heikData.getFeature();
        JSONObject dataJson = JSON.parseObject(feature);
        sb.append(formatValue(dataJson.get("reportNumber"))).append(CRT001);
        for(String k: dataJson.keySet()){
            TxSb.delete(0, TxSb.length());
            TxSb.append(k).append(CRT001);
            TxSb.append(formatValue(dataJson.get(k))).append(CRT001);
            key.set(getKey());
            val.set((sb.toString() + TxSb.toString()));
            context.write(key, val);
        }

        return true;
    }

    @Override
    public String getTableName() {
        return "kafka_babel_heika_feature_record_inc";
    }

    @Override
    public String getSubType() {
        return ".heika_feature";
    }

    @Override
    public String getType() {
        return RecordType.FUNDS_CREDIT_RECORD.toString();
    }

    @Override
    public String getComment() {
        return "黑卡特征";
    }
}
